const { PostItem, User, JoinClub, Club } = require("../db");
const { Op } = require("sequelize");

const typeMap = {
  0: "公告",
  1: "失物招领",
  2: "意见反馈",
  3: "社团活动",
};
// 新建postItem
exports.createPostItem = async (req, res) => {
  const { id } = req.user;
  const { content, type, imgUrls, title, clubId, teacherId } = req.body;
  const dateStr =
    new Date()
      .toISOString()
      .slice(0, 10)
      .replace(/-/g, "年")
      .replace(/-/g, "月") + "日";
  try {
    const postItem = await PostItem.create({
      content,
      date: dateStr,
      type: typeMap[type],
      userId: id,
      statu: 0,
      imgUrls,
      title: title,
      // UserId !!!!
      UserId: id,
      clubId: clubId || null,
      teacherId: teacherId || null,
    });
    // const tempUser = await User.findOne({ where: { id: id } });
    if (postItem)
      res.send({
        status: 200,
        message: "帖子发出成功！",
      });
    else {
      res.send({
        status: 500,
        message: "帖子发出失败！",
      });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("内部服务器错误");
  }
};

// 分页查询，获取pageSize, pageNum，type，statu，content

exports.getPostItems = async (req, res) => {
  const { pageSize, pageNum, type, statu, content, title } = req.body;
  try {
    //支持通过content模糊查询postItem
    const postItems = await PostItem.findAll({
      where: {
        type: typeMap[type],
        statu,
        content: {
          [Op.like]: `%${content}%`, // 使用 Op.like 进行模糊查询
        },
        title: { [Op.like]: `%${title}%` },
      },
      order: [["createdAt", "DESC"]],
      include: [
        {
          model: User,
          attributes: ["username", "avatarUrl"],
        },
        {
          model: Club,
          attributes: ['id', 'clubName']
        }
      ],
      limit: pageSize,
      offset: (pageNum - 1) * pageSize,
    });
    // console.log(postItems);
    const postItemsRes = postItems.map((item) => {
      return {
        id: item.id,
        type: item.type,
        content: item.content,
        statu: item.statu,
        date: item.date,
        username: item.User.username,
        avatarUrl: item.User.avatarUrl,
        // createdAt: item.createdAt,
        // updatedAt: item.updatedAt,
        commentNums: item.commentNums,
        title: item.title,
        clubId: item.Club ? item.Club.id : null,
        clubName: item.Club ? item.Club.clubName : null
      };
    });
    // // 根据postItems中的userId找到对应的username和avatarUrl
    // for (let i = 0; i < postItems.length; i++) {
    //     const user = await User.findOne({ where: { id: postItems[i].userId } });
    //     postItems[i].dataValues.avatarUrl = user.avatarUrl;
    //     postItems[i].dataValues.username = user.username;
    // }
    const resTotal = await PostItem.count({
      where: {
        type: typeMap[type],
        statu,
        content: {
          [Op.like]: `%${content}%`, // 使用 Op.like 进行模糊查询
        },
        title: { [Op.like]: `%${title}%` },
      },
    });
    res.send({
      status: 200,
      message: "获取帖子成功！",
      data: postItemsRes,
      total: resTotal,
    });
  } catch (error) {
    console.error(error);
    res.status(500).send("内部服务器错误");
  }
};
// 获取所有的postitem
exports.getAllPostItems = async (req, res) => {
  let { pageNum, pageSize, content, title, type } = req.body;
  if (type === "all" || type === undefined) type = null;
  try {
    const postItems = await PostItem.findAll({
      include: [
        {
          model: User,
          attributes: ["username", "avatarUrl"],
        },
      ],
      limit: pageSize,
      offset: (pageNum - 1) * pageSize,
      where: {
        ...(type !== null && { type: typeMap[type] }),
        title: {
          [Op.like]: `%${title}%`,
        },
        content: {
          [Op.like]: `%${content}%`,
        },
      },
    });
    const resTotal = await PostItem.count({
      where: {
        ...(type !== null && { type: typeMap[type] }),
        title: {
          [Op.like]: `%${title}%`,
        },
        content: {
          [Op.like]: `%${content}%`,
        },
      },
    });

    res.send({
      status: 200,
      message: "获取帖子成功！",
      data: postItems,
      total: resTotal,
    });
  } catch (error) {
    console.log(error);
    res.status(500).send("内部服务器错误");
  }
};
// 根据id获取postItem
exports.getPostItemById = async (req, res) => {
  const { id } = req.query;
  if (!id || id === undefined) {
    return res.status(400).send({
      status: 400,
      message: "缺少必要的id参数",
    });
  }
  // console.log('sbid', id);

  try {
    const postItem = await PostItem.findOne({
      where: {
        id: parseInt(id),
      },
      // 添加clubName字段
      include: [
        {
          model: Club,
          attributes: ["clubName"],
        },
      ],
    });
    if (postItem) {
      // postItem.dataValues.comments = comments;
      const user = await User.findOne({
        where: { id: postItem.UserId },
      });
      const postDetail = {
        ...postItem.dataValues,
        clubName: postItem.Club ? postItem.Club.clubName : null,
        avatarUrl: user.dataValues.avatarUrl,
        username: user.dataValues.username,
      };
      res.send({
        status: 200,
        message: "获取帖子成功！",
        data: postDetail,
      });
    } else {
      res.send({
        status: 404,
        message: "帖子不存在！",
      });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("内部服务器错误");
  }
};

// 根据id删除postItem
exports.deletePostItemById = async (req, res) => {
  const { id } = req.body;
  try {
    const postItem = await PostItem.findOne({
      where: {
        id,
      },
    });
    if (postItem) {
      await PostItem.destroy({
        where: {
          id,
        },
      });
      res.send({
        status: 200,
        message: "删除帖子成功！",
      });
    } else {
      res.send({
        status: 404,
        message: "帖子不存在！",
      });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("内部服务器错误");
  }
};

// 通过id修改postItem的statu（审核）
exports.updatePostItemStatu = async (req, res) => {
  const { id, statu } = req.body;
  const { id: userId } = req.user;
  try {
    const user = await User.findOne({
      where: {
        id: userId,
      },
    });
    if (user.role === "jyu_admin") {
      const postItem = await PostItem.findOne({
        where: {
          id,
        },
      });
      if (postItem) {
        await PostItem.update(
          {
            statu,
          },
          {
            where: {
              id,
            },
          }
        );
        res.send({
          status: 200,
          message: "帖子状态修改！",
        });
      } else {
        res.send({
          status: 404,
          message: "帖子不存在！",
        });
      }
    } else {
      res.send({
        status: 403,
        message: "权限不足！",
      });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send("内部服务器错误");
  }
};

// 根据用户id、statu、获取postItem分页列表
exports.getPostItemByUserId = async (req, res) => {
  // statu 可能为空
  const { id: userId } = req.user;
  let { statu, pageNum, pageSize, content, type } = req.body;
  if (type === "all" || type === undefined) type = null;
  if (!content) content = "";
  console.log(type, content);
  const offset = (pageNum - 1) * pageSize;
  if (statu === "all") {
    try {
      const resTotal = await PostItem.count({
        where: {
          userId,
          ...(type !== null ? { type: typeMap[type] } : {}),
        },
      });
      const postItems = await PostItem.findAll({
        where: {
          userId,
          ...(type !== null ? { type: typeMap[type] } : {}),
        },
        content: {
          [Op.like]: `%${content}%`,
        },
        order: [["createdAt", "DESC"]],
        include: [
          {
            model: User,
            attributes: ["username", "avatarUrl"],
          },
          {
            model: Club,
            attributes: ["clubName"],
          },
        ],
        offset,
        limit: pageSize,
      });

      const postItemsRes = postItems.map((item) => {
        return {
          content: item.content,
          statu: item.statu,
          date: item.date,
          username: item.User.username,
          avatarUrl: item.User.avatarUrl,
          commentNums: item.commentNums,
          type: item.type,
          id: item.id,
          title: item.title,
          clubId: item.clubId,
          clubName: item.Club ? item.Club.clubName : null,
        };
      });
      if (postItems.length > 0) {
        res.send({
          status: 200,
          message: "获取个人发布的帖子成功！",
          data: postItemsRes,
          total: resTotal,
        });
      } else {
        res.send({
          status: 404,
          message: "该用户未发布过帖子",
        });
      }
    } catch (error) {
      console.error(error);
      res.status(500).send("内部服务器错误");
    }
  }
  // statu为3  返回的数据提供给社团管理员进行审核工作
  else if (statu === 3) {
    //待审核需要验证身份
    const userInfo = await User.findOne({
      where: {
        id: userId,
      },
    });
    if (userInfo.role === "jyu_admin") {
      try {
        // 合并计数和查找逻辑
        // const resTotal = await PostItem.count({
        //     where: {
        //         [Op.or]: [
        //             { // 查询所有   已通过指导老师审核的  社团活动
        //                 statu: 3,
        //                 type: '社团活动',
        //             },
        //             { // 查询所有   待审核的    类型非社团活动的    帖子
        //                 statu: 0,
        //                 type: {[Op.ne]: '社团活动'},
        //             },
        //         ]
        //     },
        // });

        // 查询已通过指导老师审核（statu === 3）的社团活动（type === '社团活动'）以及所有待审核的类型非社团活动的帖子（type !== '社团活动' && statu === 0）
        const postItems = await PostItem.findAndCountAll({
          where: {
            [Op.or]: [
              {
                // 查询所有   已通过指导老师审核的  社团活动
                statu: 3,
                type: "社团活动",
                ...(type !== null ? { type: typeMap[type] } : {}),
              },
              {
                // 查询所有   待审核的    类型非社团活动的    帖子
                statu: 0,
                type: { [Op.ne]: "社团活动" },
                ...(type !== null ? { type: typeMap[type] } : {}),
              },
            ],
          },
          content: {
            [Op.like]: `%${content}%`,
          },
          include: [
            {
              model: User,
              attributes: ["username", "avatarUrl"],
            },
            {
              model: Club,
              attributes: ["clubName"],
            },
          ],
          // 排序
          order: [["createdAt", "DESC"]],
          // 分页
          offset,
          limit: pageSize,
        });
        const postItemsRes = postItems.rows.map((item) => {
          return {
            id: item.id,
            content: item.content,
            statu: item.statu,
            date: item.date,
            username: item.User.username,
            avatarUrl: item.User.avatarUrl,
            title: item.title,
            type: item.type,
            clubId: item.clubId,
            clubName: item.Club ? item.Club.clubName : null,
          };
        });
        res.send({
          status: 200,
          message: "获取审核列表成功！",
          data: postItemsRes,
          total: postItems.count,
        });
      } catch (error) {
        console.error(error);
        res.status(500).send("内部服务器错误");
      }
    } else {
      res.send({
        status: 403,
        message: "权限不足！",
      });
    }
  }
  // statu为0  指导老师审核
  else if (statu === 0) {
    try {
      // 查询所有与该老师相关联的社团的社团活动
      // 先根据userInfo查询该老师管理的社团
      const joinClubRes = await JoinClub.findAll({
        where: {
          userId, // id
          role: "club_teacher", // 身份为指导老师
          statu: 1, // 已通过审核
        },
      });
      const clubIdRes = joinClubRes.map((item) => {
        return item.dataValues.clubId;
      });
      // console.log(clubIdRes);

      // 如果clubIdRes为空    说明该用户不是任何一个社团的指导老师
      if (clubIdRes.length === 0) {
        res.send({
          status: 403,
          message: "",
        });
      }

      // 根据clubIdRes查询所有对应的社团活动帖子
      const postItems = await PostItem.findAndCountAll({
        where: {
          clubId: { [Op.in]: clubIdRes }, // 社团id
          type: "社团活动", // 帖子类型为社团活动
          teacherId: userId,
          statu: 0, // statu为0  表示未通过指导老师审核
        },
        content: {
          [Op.like]: `%${content}%`,
        },
        include: [
          {
            model: User,
            attributes: ["username", "avatarUrl"],
          },
          {
            model: Club,
            attributes: ["clubName"],
          },
        ],
        // 排序
        order: [["createdAt", "DESC"]],
        // 分页
        offset,
        limit: pageSize,
      });

      // console.log(postItemRes)
      // 处理数据并返回
      const postItemsRes = postItems.rows.map((item) => {
        return {
          id: item.id,
          content: item.content,
          statu: item.statu,
          date: item.date,
          username: item.User.username,
          avatarUrl: item.User.avatarUrl,
          title: item.title,
          type: item.type,
          clubId: item.clubId,
          clubName: item.Club ? item.Club.clubName : null,
        };
      });
      res.send({
        status: 200,
        message: "获取审核列表成功！",
        data: postItemsRes,
        total: postItems.count,
      });
    } catch (error) {
      console.error(error);
      res.status(500).send({
        status: 500,
        message: "内部服务器错误",
      });
    }
  }
  // TODO 还有一种情况是statu===2没写  暂时用不上   以后可能管理后台会用
  else {
    res.send({
      status: 400,
      message: "参数不正确！",
    });
  }
};
//获得帖子情况数量
exports.getPostItemsCount = async (req, res) => {
  try {
    const resPostTotal = await PostItem.count();
    const resPassPostTotal = await PostItem.count({
      where: {
        statu: 1,
      },
    });
    const resAduditPostTotal = await PostItem.count({
      where: {
        [Op.or]: [
          {
            statu: 0,
          },
          {
            statu: 3,
            type: "社团活动",
          },
        ],
      },
    });
    const resNoPassTotal = await PostItem.count({
      where: {
        statu: 2,
      },
    });
    res.send({
      status: 200,
      message: "获取帖子情况统计成功",
      data: [
        resPostTotal,
        resPassPostTotal,
        resAduditPostTotal,
        resNoPassTotal,
      ],
    });
  } catch (error) {
    console.log(error);
    res.status(500).send("内部服务器错误 ");
  }
};
